pipeline {
    agent any
    
    tools {
        maven 'maven3.9'
        jdk 'JDK1.8'
    }
    
    parameters {
        string(
            name: 'ImageVersion',
            description: '镜像版本',
            defaultValue: '1.0.0'
        )
        booleanParam(
            name: 'OnlyDeploy', 
            defaultValue: false, 
            description: '是否仅部署前端工程'
        )
    }
    
    environment {
        //GIT仓库主机地址
        HOST_GIT="http://git.szjingshuo.top:3000"
        // 管理平台前端工程名称
        PROJECT_REPO_NAME="eom-admin-ui"
        // 工程构建镜像和docker镜像名称
        PROEJCT_UI_NAME="eom-admin-ui"
        // 部署目标主机
        PROJECT_DEPLOY_HOST_NAME="eom-test-02"
        // compose文件上层目录名称
        PROJECT_GROUP_NAME="eom2"

        GIT_REPO_USER_ID="goes_for_jenkins"
        //从GIT获取源码地址
        GIT_REPO_CONSOLE_URL="${env.HOST_GIT}/${env.PROJECT_GROUP_NAME}/${env.PROJECT_REPO_NAME}.git"
        //源代码分支(可修改为参数)
        PULL_SOURCE_BRANCH="${params.branch}"

        DOCKER_BUILD_HOST_NAME="docker.szjingshuo.top"
        DOCKER_REGISTRY_HOST_NAME="reg.szjingshuo.top"
        DOCKER_IMAGE_NODE_NAME='node:16.15.0-alpine3.15'
        DOCKER_IMAGE_NGINX_NAME='nginx:1.23.4-alpine3.17'
        DOCKER_TEMP_IMG_NAME="${env.PROEJCT_UI_NAME}_tmp:${params.ImageVersion}"
        DOCKER_IMAGE_PROJECT_UI_NAME="${env.DOCKER_REGISTRY_HOST_NAME}/${env.PROJECT_GROUP_NAME}/${env.PROEJCT_UI_NAME}-${params.branch}:${params.ImageVersion}"
        //Docker主机上传临时目录
        PROJECT_BUILD_WORKSPACE="/tmp/${env.PROJECT_REPO_NAME}"

    
        DATE_TIME = sh(returnStdout: true, script: 'date "+%Y%m%d_%H:%M:%S"').trim()
    }

    stages {
        stage("拉取管理平台仓库源码") {
            steps {
                dir("${env.PROJECT_REPO_NAME}") {
                    echo "开始拉取控制台工程源码，URL=>${env.GIT_REPO_CONSOLE_URL}"
                    git branch:"${params.branch}", credentialsId: "${env.GIT_REPO_USER_ID}", url:"${env.GIT_REPO_CONSOLE_URL}"
                    echo "代码拉取成功"  
                }
            }
        }
        // stage("开始构建前端工程应用镜像") {
        //     steps {
        //         sshPublisher(
        //             publishers: [
        //                 sshPublisherDesc(
        //                     configName: "${env.DOCKER_BUILD_HOST_NAME}", 
        //                     transfers: [
        //                         //复制Console前端源码至Docker构建服务器,并开始构建
        //                         sshTransfer(
        //                             execTimeout: 240000, 
        //                             remoteDirectory: "/tmp/${env.PROJECT_REPO_NAME}", 
        //                             removePrefix: "${env.PROJECT_REPO_NAME}", 
        //                             sourceFiles: "${env.PROJECT_REPO_NAME}/**",
        //                             exclude: ".git/**",
        //                             execCommand: """
        //                                 # 判断Node基础镜像是否存在，如果不存在则先下载
        //                                 if [[ "" == "\$(docker images -q ${env.DOCKER_IMAGE_NODE_NAME} 2> /dev/null)" ]];then
        //                                     echo "开始下载NodeJS基础镜像${env.DOCKER_IMAGE_NODE_NAME}"
        //                                     docker pull ${env.DOCKER_IMAGE_NODE_NAME}
        //                                     echo "NodeJS基础镜像下载完成"
        //                                 fi
        //                                 if [[ "" == "\$(docker images -q ${env.DOCKER_IMAGE_NGINX_NAME} 2> /dev/null)" ]];then
        //                                     echo "开始下载NodeJS基础镜像${env.DOCKER_IMAGE_NGINX_NAME}"
        //                                     docker pull ${env.DOCKER_IMAGE_NGINX_NAME}
        //                                     echo "Nginx基础镜像下载完成"
        //                                 fi
        //                                 echo "开始构建Console前端工程"
        //                                 docker build -t ${DOCKER_IMAGE_PROJECT_UI_NAME} /tmp/${env.PROJECT_REPO_NAME}
        //                                 echo "Console前端工程镜像构建完成"
        //                                 docker push ${DOCKER_IMAGE_PROJECT_UI_NAME}
        //                                 echo "镜像【${DOCKER_IMAGE_PROJECT_UI_NAME}】上传仓库成功"
        //                                 # 删除之前同版本镜像
        //                                 if [[ "" == "\$(docker images -q ${DOCKER_IMAGE_PROJECT_UI_NAME} 2> /dev/null)" ]];then
        //                                     echo "镜像【${DOCKER_IMAGE_PROJECT_UI_NAME}】已存在，将删除后重新上传"
        //                                     docker rmi ${DOCKER_IMAGE_PROJECT_UI_NAME}
        //                                     echo "镜像【${DOCKER_IMAGE_PROJECT_UI_NAME}】删除成功"
        //                                 fi
        //                                 # 删除临时文件
        //                                 rm -rf /tmp/${env.PROJECT_REPO_NAME}
        //                             """
        //                         )
        //                     ],
        //                     verbose: true
        //                 )
        //             ]
        //         )
        //         echo "前端工程应用镜像构建完成"
        //     }
        // }

        stage("部署中间件配置文件") {
            steps {
                script {
                
                    //创建文件上传文件夹 upload
                    sshPublisher(
                        publishers: [
                            sshPublisherDesc(
                                configName: "${env.PROJECT_DEPLOY_HOST_NAME}",
                                transfers: [
                                    sshTransfer(
                                        execTimeout: 120000,
                                        remoteDirectory: "${env.PROJECT_BUILD_WORKSPACE}/confs",
                                        removePrefix: "${PROJECT_REPO_NAME}/deploy/confs",
                                        sourceFiles: "${PROJECT_REPO_NAME}/deploy/confs/**",
                                        execCommand: """
                                            echo "检测目录/data/nginx"
                                            if [[ ! -d "/data/nginx/" ]]; then
                                                mkdir -p /data/nginx/{data,conf,log}
                                                echo "/data/nginx目录创建成功"
                                            else
                                                echo "/data/nginx目录已存在"
                                            fi
                                            echo "拷贝nginx配置文件到服务器"
                                            cp -rf ${env.PROJECT_BUILD_WORKSPACE}/confs/nginx/* /data/nginx/conf/
                                        """
                                    )
                                ],
                                verbose: true
                            )
                        ]
                    ) 
                }
            }
        }

        stage("部署前端DockerCompose文件") {
            steps {
                script {
                    def docker_net_name="net_${env.PROJECT_GROUP_NAME}"
                    def docker_compose_dir="/opt/${env.PROJECT_GROUP_NAME}"
                    def docker_image_version="${params.branch}:${params.ImageVersion}"
                    sh """
                        ls -l
                    """
                    sshPublisher(
                        publishers: [
                            sshPublisherDesc(
                                configName: "${env.PROJECT_DEPLOY_HOST_NAME}", 
                                transfers: [
                                    //复制Console前端源码至Docker构建服务器,并开始构建
                                    sshTransfer(
                                        execTimeout: 120000, 
                                        remoteDirectory: "${docker_compose_dir}",
                                        removePrefix: "${PROJECT_REPO_NAME}/deploy/compose",
                                        sourceFiles: "${PROJECT_REPO_NAME}/deploy/compose/**",
                                        exclude: ".git/**",
                                        execCommand: """

                                            # 检测容器网络是否已创建
                                            if [ "0" -eq "\$(docker network ls | grep ${docker_net_name} | wc -l)" ]; then
                                                docker network create ${docker_net_name}
                                                echo "容器网络【${docker_net_name}】创建成功"
                                            fi

                                            # 执行admin管理前端服务启停
                                            if [[ \$(docker-compose ls -q | grep frontend-service) ]]; then
                                                docker-compose -p frontend-service -f ${docker_compose_dir}/frontend-service.yaml down
                                                echo "应用中间件已停止"
                                            fi

                                            # 启动前端服务
                                            docker-compose -p frontend-service -f ${docker_compose_dir}/frontend-service.yaml up -d
                                            echo "前端服务已启动"

                                            
                                        """
                                    )
                                ],
                                verbose: true
                            )
                        ]
                    )
                    echo "前端工程部署完成"
                }
            }
        }
    }
}